package cn.tedu.egweibo1.controller;

import cn.tedu.egweibo1.base.response.JsonResult;
import cn.tedu.egweibo1.base.response.StatusCode;
import cn.tedu.egweibo1.mapper.WeiboMapper;
import cn.tedu.egweibo1.pojo.dto.WeiboAddParam;
import cn.tedu.egweibo1.pojo.entity.Weibo;
import cn.tedu.egweibo1.pojo.vo.UserVO;
import cn.tedu.egweibo1.pojo.vo.WeiboDetailVO;
import cn.tedu.egweibo1.pojo.vo.WeiboIndexVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Validated
@RestController
@Api(tags = "02.微博模块")
@Slf4j
@RequestMapping("/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    @PostMapping("insert")
    @ApiOperation("发布微博功能")
    @ApiOperationSupport(order = 10)
    public JsonResult insert(@RequestBody WeiboAddParam weiboAddParam, @ApiIgnore HttpSession session){
        log.debug("weiboAddParam:{}", weiboAddParam);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }

        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboAddParam, weibo);
        weibo.setCreateTime(new Date());
        weibo.setUserId(userVO.getId());
        weiboMapper.insertWeibo(weibo);
        return JsonResult.ok();
    }


    @GetMapping("selectIndex")
    @ApiOperation("微博首页列表功能")
    @ApiOperationSupport(order = 20)
    public JsonResult selectIndex(){
        List<WeiboIndexVO> weiboIndexVOS = weiboMapper.selectIndex();

        return JsonResult.ok(weiboIndexVOS);
    }


    @ApiOperation("微博详情页功能")
    @GetMapping("selectById")
    @ApiImplicitParam(name = "id", value = "微博ID", required = true, dataType = "Long")
    public JsonResult selectById(@Range(min = 1, max = 300, message = "id必须在1-100之间") @RequestParam Long id){
        log.debug("id = " + id);
        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id);

        return JsonResult.ok(weiboDetailVO);
    }
}
